(function (window, $, undefined) {
  'use strict';


  var dictData = {
    orderChannel: {
      '1': '小程序',
      '2': '管理后台',
      '3': 'iOS',
      '4': '安卓'
    },
    orderType: {
      '1': '立即接机',
      '2': '立即接站',
      '3': '预约接机',
      '4': '预约接站',
      '5': '预约送机',
      '6': '预约送站',
      '7': '预约用车',
      '8': '立即用车'
    },
    bookModel: {
      '1': '经济型',
      '2': '豪华型',
      '3': '商务七座'
    },
    payType: {
      '1': '乘客支付',
      '2': '司机代付'
    },
    payChannel: {
      '1': '微信',
      '2': '支付宝',
      '3': '银联',
      '4': '账户扣款',
      '5': '企业代扣',
      '9': '其他'
    },
    orderState: { //订单状态
      '1': '等待接单',
      '2': '预约成功',
      '3': '已派车',
      '4': '司机出发',
      '5': '司机到达出发地',
      '6': '乘客已上车',
      '7': '行程中',
      '8': '行程结束待计算价格',
      '9': '行程结束待付款',
      '10': '标注已付款（用于司机代付）',
      '11': '已支付（确实已付款，来自支付渠道的返回结果）',
      '12': '已评价',
      '13': '已取消',
      '14': '派车失败下单失败',
      '15': '运力不足下单失败',
      '20': '已关闭',
    },
    orderModel: {//派单类型
      '1': '自动派单',
      '2': '手动派单'
    },
    adjustType: {//调价类型
      '1': '采用预估价',
      '2': '协商后价格',
      '3': '其他价格'
    }
  };

  var cityData = {};

  var orderData = {};

  main(function () {

    //获取操作人并修改
    $("span[data-opertator]").text(oUser.account)

    var $tableUnpaid = $('#table-unpaid');
    util.jqGrid($tableUnpaid, {
      url:ajaxURL.ORDER+'/order/queryOrderIngList',
      serializeGridData: function (postData) {
        var newData = {
          pageNum:postData.pageNum,
          pageSize:postData.pageSize,
          orderNo:postData.orderNo,
          autoNo:postData.autoNo,
          driverPhone:postData.driverPhone,
          placingUserPhone:postData.placingUserPhone,
          orderState: 9 // 未付款
        };
        return newData
      },
      datatype: 'json',
      autowidth: true,
      height: $(window).height() - 350,
      multiselect: true,
      multiboxonly: true,
      shrinkToFit: false,
      colModel: [
        { name: '_id', key: true, hidden: true },
        {
          label: '订单编号（ID）', name: 'orderNo', width: 150, formatter: function (v, o, r) {
            return '<a href="javascript:;" class="view" data-id="' + r.orderNo + '">' + v + '</a>';
          }
        },
        { label: '创建时间', name: 'createTime', width: 150, formatter: function (v) {
          return util.dateFormat(v);
        } },
        { label: '用车时间', name: 'planDepartTime', width: 150, formatter: function (v) {
          return util.dateFormat(v);
        } },
        { label: '城市', name: 'planOrigCityId', width: 80, formatter: function (v) {
          return cityData[v] || '';
        } },
        {
          label: '服务类型', name: 'orderType', width: 80, formatter: function (v) {
          return dictData.orderType[v] || '';
        } },
        {
          label: '用车类型', name: 'model', width: 80, formatter: function (v) {
          return dictData.bookModel[v] || '';
        } },
        { label: '车牌号', name: 'autoNo', width: 150 },
        { label: '下单人', name: 'placingUserPhone', width: 150 },
        { label: '用车人', name: 'passengerPhone', width: 150 },
        { label: '司机ID', name: 'driverId', width: 80 },
        { label: '司机电话', name: 'driverPhone', width: 150 },
        { label: '累计催收次数', name: '', width: 100 }
      ],
      loadComplete: function (res) {
        orderData = {};
        if (res && res.data) {
          $.each(res.data, function (_, item) {
            orderData[item.orderNo] = item;
          });
        }
      },
      pager: '#pager-unpaid'
    });


    // 获取城市列表
    util.get(ajaxURL.ORGANIZATION + '/city/getCityList?pageNum=1&pageSize=99999', function (res) {
      util.selectHtml($('[name="cityId"]'), res.data, 'cityId', 'name', '请选择');
      $.each(res.data, function (_, item) {
        cityData[item.cityId] = item.name;
      });
      searchTable();
    });

    function searchTable() {
      var data = util.formData('#form-search');
      util.searchGrid($tableUnpaid, data);
    }
    $('#search-btn').click(searchTable)

    // 字典下拉数据
    util.selectHtml('[name="orderType"]', dictData.orderType, '', '', '请选择');
    util.selectHtml('[name="bookModel"]', dictData.bookModel, '', '', '请选择');
    util.selectHtml('[name="orderChannel"]', dictData.orderChannel, '', '', '请选择');
    util.selectHtml('[name="payType"]', dictData.payType, '', '', '请选择');
    util.selectHtml('[name="payChannel"]', dictData.payChannel, '', '', '请选择');
    util.selectHtml('[name="orderState"]', dictData.orderState, '', '', '请选择');

    //服务类型
    util.getDict('orderType', 'orderType').then(function (data) {
      util.selectHtml('[name="orderType"]', data, 'value', 'name', '请选择');
      $.each(data, function (_, item) {
        dictData.orderType[item.value] = item.name;
      });
    });

    // 创建时间段
    laydate.render({
      range: '至',
      elem: '#created-time',
      done: function (value, date, endDate) {
        var temp = value.split('至');
        $('#created-time').next().val($.trim(temp[0])).next().val($.trim(temp[1]));
      }
    });

    // 自动催款设置
    $('#btn-textSetting').click(function () {
      $('#layer-unpaid-textSetting').find(':input').removeAttr('disabled');
      util.layerOpen3({
        title: '自动催款设置',
        content: $('#layer-unpaid-textSetting'),
        cancel: function (index) {
          layer.confirm('确定退出当前页面？', {
            btn: ['确定', '再想一想'],
            yes: function (idx) {
              layer.close(index);
              layer.close(idx);
            }
          });
          return false;
        }
      });
    });

    // 查看订单
    var $formOrderView = $('#layer-unpaid-view');
    $tableUnpaid.on('click', '.view', function () {
      var $this = $(this);
      var id = $this.data('id');
      // 根据 id 请求数据
      var data = $.extend(true,{},orderData[id]);
      data.orderModel = dictData.orderModel[1];
      //d-header处理
      $formOrderView.find('[data-clientId]').text(data.orderNo);
      $formOrderView.find('[data-clientStatus]').text(dictData.orderState[data.orderState]);
      $('input[name="factFinalPrice"]').attr('disabled',true);
      $('select[name="adjustType"]').attr('disabled',true);
      $('.submit').css('display','none');

      //行程时间 = 实际到达时间desttime-实际出发时间deptime
      data.totalTime = data.destTime-data.depTime;
      data.totalTime = util.dateFormat(data.totalTime)

      //时间处理
      data.depTime = util.dateFormat(data.depTime);//实际出发时间
      data.destTime = util.dateFormat(data.destTime);//到达时间
      data.updateTime = util.dateFormat(data.updateTime);//记录更新时间
      data.paiedTime = util.dateFormat(data.paiedTime);//付款时间
      //实际行驶时间
      if(data.driveTime){
        data.driveTime = data.driveTime+'分钟';
      }

      //价格 里程格式处理
      data.planPrice = util.price(data.planPrice);
      data.factFinalPrice = util.price(data.factFinalPrice);
      // data.startMile = util.toKilometer(data.startMile);
      // data.endMile = util.toKilometer(data.endMile);

      util.resetForm($formOrderView);
      util.fillForm($formOrderView, data);


      util.layerOpen3({
        title: '订单详情',
        content: $('#layer-unpaid-view')
      });
    });

    // 短信催收
    $('#btn-text').click(util.oneCheck($tableUnpaid, function (id) {
      layer.confirm('确定发出催收短信吗？', {
        btn: ['确定', '再想一想']
      }, function () {
        util.tip.warn('发送催收短信...');
      });
    }));

    var $layerUnpaidAccount = $('#layer-unpaid-account');
    $layerUnpaidAccount.find('[name="adjustType"]').change(function(){
      var $this = $(this);
      var $priceChange = $layerUnpaidAccount.find('[name="factFinalPrice"]');
      if($this.val()==1){
        var s = $layerUnpaidAccount.find('[name="planPrice"]').val();
        $priceChange.val(parseFloat(s))
      }else{
        $priceChange.val('')
      }

    })

    //调账验证
    var $formUnpaidAccount = $('#form-unpaid-account');
    var $validateUnpaidAccount = $formUnpaidAccount.validate({
      rules: {
        factFinalPrice: {
          required: true,
          number: true,
          min: 0.01
        },
        adjustType: { required: true }
      },
      messages: {
        factFinalPrice: {
          required: '请输入调价金额',
          number: '请正确输入价格',
          min: '输入最小金额为0.01'
        },
        adjustType: { required: '请选择调价类型' }
      }
    });

    // 调账
    var sendData = {};
    $('#btn-account').click(util.oneCheck($tableUnpaid, function (id) {
      // 只开放实付金额
      // $('#layer-supplier-add').find(':input').removeAttr('disabled');
      var $this = $('.success td:nth-child(3)').attr('title');
      $('input[name="factFinalPrice"]').removeAttr('disabled');
      $('select[name="adjustType"]').removeAttr('disabled');
      $('.submit').css('display','block');

      var id = $this;
      // sendData = orderData[id];
      var data = $.extend(true,{},orderData[id]);
      // 根据 id 请求数据

      //d-header处理
      $layerUnpaidAccount.find('[data-clientId]').text(data.orderNo);
      $layerUnpaidAccount.find('[data-clientStatus]').text(dictData.orderState[data.orderState]);

      //价格 里程格式处理
      data.planPrice = util.price(data.planPrice);
      data.factFinalPrice = util.price(data.factFinalPrice);
      // data.startMile = util.toKilometer(data.startMile);
      // data.endMile = util.toKilometer(data.endMile);

      //时间处理
      data.depTime = util.dateFormat(data.depTime);//实际出发时间
      data.destTime = util.dateFormat(data.destTime);//到达时间
      data.updateTime = util.dateFormat(data.updateTime);//记录更新时间
      data.paiedTime = util.dateFormat(data.paiedTime);//付款时间

      util.resetForm($layerUnpaidAccount);
      util.fillForm($layerUnpaidAccount, data);
      $('.submit').click(function(){
        if($validateUnpaidAccount.form()){
          var data = util.formData($layerUnpaidAccount, true);
          //上步操作得到的sendData，作为调账时的数据修改后发送给后台
          var sendFactFinalPrice = $layerUnpaidAccount.find('[name="factFinalPrice"]').val();
          sendData.price = Number(sendFactFinalPrice * 100).toFixed(0);
          sendData.orderNo = $layerUnpaidAccount.find('[name="orderNo"]').val();
          sendData.adjustType = $layerUnpaidAccount.find('[name="adjustType"]').val();

          layer.confirm('确认调账？',{
            btn:['确定','再想一想']
          }, function () {//调账接口   ,orderId,price,adjustType
            $.post(ajaxURL.PRICE + '/actualprice/changePrice', $.param(sendData) , function (res) {
              layer.closeAll();
              util.tip.success('调账成功!');
              $tableUnpaid.trigger('reloadGrid');
            })

          })
          // util.tip.warn('调帐')
        }
      })

      util.layerOpen3({
        title: '订单调账',
        content: $('#layer-unpaid-account')
      });
    }));


    // 导出
    $('#btn-export').click(function () {
      util.tip.warn('导出操作...');
    });

  });


})(window, jQuery);
